package com.hd.crdao.fragment;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.google.gson.Gson;
import com.hd.crdao.R;
import com.hd.crdao.activity.FirmOrderActivity;
import com.hd.crdao.base.BaseFragment;
import com.hd.crdao.bean.CarVinRecognizeBean;
import com.hd.crdao.config.Constants;
import com.hd.crdao.proxy.RecognizeService;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.ChineseUtils;
import com.hd.crdao.utils.FileUtils;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.ExpandHeadView;
import com.hd.crdao.wrapper.AllCapTransformationMethod;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 *
 *@author Administrator
 *@date 2017/6/26 0026
 */
public class QueryFrangment extends BaseFragment {
    private static final int REQUEST_CODE_GENERAL_WEBIMAGE = 100;
    @BindView(R.id.head)
    ExpandHeadView mHead;
    @BindView(R.id.et_vin)
    EditText mEtVin;
    @BindView(R.id.bt_query)
    Button mBtQuery;
    @BindView(R.id.recognizeVin)
    ImageView mRecognizeVin;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_query;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this, mViewRoot);
    }

    @Override
    protected void initListener() {
        mHead.getLeftArrowLL().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
    }

    @Override
    protected void initData() {
        mEtVin.setTransformationMethod(new AllCapTransformationMethod());
        OCR.getInstance().initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                ALog.d(token);
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
            }
        }, UIUtils.getContext(), getString(R.string.OCR_AK1), getString(R.string.OCR_SK1));
    }


    @OnClick({R.id.bt_query, R.id.recognizeVin})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.bt_query:
                searchResult();
                break;
            case R.id.recognizeVin:
                recognizeVin();
                break;
        }


    }

    /**
     * 识别出VIN妈
     */
    private void recognizeVin() {
        Intent intent = new Intent(UIUtils.getContext(), CameraActivity.class);
        intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                FileUtils.getSaveFile(getContext()).getAbsolutePath());
        intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                CameraActivity.CONTENT_TYPE_GENERAL);
        startActivityForResult(intent, REQUEST_CODE_GENERAL_WEBIMAGE);
    }

    @Override
    public void onActivityResult(final int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_GENERAL_WEBIMAGE && resultCode == Activity.RESULT_OK) {
            RecognizeService.recWebimage(FileUtils.getSaveFile(getContext()).getAbsolutePath(),
                    new RecognizeService.ServiceListener() {
                        @Override
                        public void onResult(String result) {
                            ALog.d(result);
                           // MyToast.show(result);
                            if (result.contains("log_id")) {
                                CarVinRecognizeBean carVinRecognizeBean = new Gson().fromJson(result, CarVinRecognizeBean.class);
                                String words = carVinRecognizeBean.getWords_result().get(0).getWords();
                                String vinCode = ChineseUtils.dealWithWords(words);
                                mEtVin.setText(vinCode);
                            } else {
                                MyToast.show("识别失败");
                            }
                        }

                    }

            );
        }
        super.onActivityResult(requestCode, resultCode, data);
    }




    /**
     * 输入VIN,得到搜索的结果
     */
    private void searchResult() {
        String businessid = SPUtils.getString("businessid", "");
        String vin = mEtVin.getText().toString().trim().toUpperCase();
        ALog.d("businessid=" + businessid);
        if (TextUtils.isEmpty(businessid)) {
            return;
        } else if (TextUtils.isEmpty(vin)) {
            MyToast.show("请填写VIN码");
            return;
        }
        try {
            OkHttpUtils.post().url(Constants.QUERY_URL).addParams("carBusinessId", businessid).addParams("vin", vin)
                    .build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    MyToast.show("查询失败,请检查网络");
                }

                @Override
                public void onResponse(String response, int id) {
                    ALog.d(response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String success = (String) jsonObject.get("success");
                        String message = (String) jsonObject.get("message");
                        if (TextUtils.equals("00", success)) {
                            String vin = (String) jsonObject.get("vin");
                            String buyid = (String) jsonObject.get("buyid");
                            String payListId = (String) jsonObject.get("payListId");
                            Intent intent = new Intent(UIUtils.getContext(), FirmOrderActivity.class);
                            intent.putExtra("vin", vin);
                            intent.putExtra("buyid", buyid);
                            intent.putExtra("payListId", payListId);
                            startActivity(intent);
                        } else {
                            MyToast.show(message);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
